//
//  XQDiskMemoryTool.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/16.
//

import UIKit
import MachO
import Darwin

class XQDiskMemoryTool: NSObject {

    static func totalMemorySize() -> String {
        let size = ProcessInfo.processInfo.physicalMemory
        return formatMemory(bytes: Int64(size))
    }
    
    static func availableMemorySize() -> String {
        var vmStats: vm_statistics_data_t = vm_statistics_data_t()
        var number: mach_msg_type_number_t = UInt32(MemoryLayout<vm_statistics_data_t>.size / MemoryLayout<integer_t>.size)
        let status: kern_return_t = withUnsafeMutablePointer(to: &vmStats) {
            $0.withMemoryRebound(to: integer_t.self, capacity: Int(number)) {
                host_statistics(mach_host_self(), HOST_VM_INFO, $0, &number)
            }
        }
        if status != KERN_SUCCESS {
            return ""
        }
        let pageSize: Int64 = Int64(vm_page_size)
        let availableMemorySize = (pageSize * Int64(vmStats.free_count + vmStats.inactive_count))
        return formatMemory(bytes: availableMemorySize)
    }
    
    static func getStorageSizes() -> String {
        do {
            let systemAttributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String)
            
            let totalSpace = systemAttributes[.systemSize] as? NSNumber ?? 0
            
            return formatMemory(bytes: totalSpace.int64Value)
        } catch {
            return ("0")
        }
    }
    
    static func availableStorageSize() -> String {
        let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
        do {
            let resourceValues = try tempDirectoryURL.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
            if let availableCapacity = resourceValues.volumeAvailableCapacityForImportantUsage {
                return "\(availableCapacity)"
            } else {
                return "0"
            }
        } catch {
            return "0"
        }
    }
    
    static func formatMemory(bytes: Int64) -> String {
        return "\(bytes)"
    }
}
